<template>
  <view class="page-container min-h-screen flex flex-col bg-gray-100">
    <!-- 固定的顶部区域 -->
    <view class="fixed-header">
      <!-- 顶部导航 -->
      <S1Header title="订单管理" :on-back="onBack" />

      <!-- 搜索框 -->
      <view class="border-b border-gray-200 bg-white px-4 py-2">
        <view class="mx-auto flex items-center justify-between">
          <view class="flex-1">
            <view class="h-[37px] flex items-center border border-[#e4eaf2] rounded-[18px] bg-[#f5f7fa] px-3">
              <image src="https://ceshiweb.picaime.com/static/images/search.png" class="mr-10rpx h-36rpx w-36rpx" />
              <input
                v-model="keyword" class="flex-1 text-sm" placeholder="搜索买家名称或单号" confirm-type="search"
                @confirm="onSearch"
              >
              <view v-if="keyword" class="h-40rpx w-40rpx flex items-center justify-center" @click="clearKeyword">
                <image class="h-36rpx w-36rpx" src="https://ceshiweb.picaime.com/static/images/close.png" />
              </view>
              <view class="h-40rpx w-40rpx flex items-center justify-center" @click="onFilter">
                <image class="h-36rpx w-36rpx" src="https://ceshiweb.picaime.com/static/images/filter.png" />
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view
      scroll-y class="order-list" refresher-enabled :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh" @scrolltolower="loadMore"
    >
      <!-- 订单项 -->
      <view
        v-for="(order, index) in orders" :key="order.id || index"
        class="mx-3 mb-3 overflow-hidden rounded-lg bg-white shadow-sm"
      >
        <!-- 顶部区域: 订单信息区 -->
        <view class="px-3 pb-1 pt-2">
          <view class="mb-1 flex justify-between">
            <text class="text-sm text-[#ff6b01] font-medium">
              #{{ order.piao_num || order.orderId }}
            </text>
            <text class="text-xs text-gray-400">
              {{ order.add_time || order.createTime }}
              <text v-if="order.user">
                开单人：{{ order.user.name || order.opener }}
              </text>
            </text>
          </view>
        </view>

        <!-- 内容和按钮并排区域 -->
        <view class="flex px-3 pb-2">
          <!-- 左侧内容区（带橙色边框） -->
          <view class="mr-2 w-[60%] flex-1 border border-[#ff6b01] rounded p-1.5">
            <view class="flex-1">
              <view class="mb-1 flex justify-between">
                <text class="font-medium">
                  {{ order.maijia || order.buyerName }}
                </text>
                <text
                  class="text-sm" :class="order.status !== 0
                    ? 'text-[#00b510]'
                    : 'text-[#ff6b01]'
                  "
                >
                  {{ order.status !== 0 ? '实收' : '下欠' }}：
                  <text>
                    {{
                      order.status !== 0 ? order.shishou : order.yingshou
                    }}
                  </text>
                </text>
              </view>
              <view class="flex justify-between">
                <text class="block truncate pr-2 text-xs text-gray-400">
                  {{ formatOrderDetail(order.order_detail) }}
                </text>
              </view>
            </view>
          </view>

          <!-- 右侧按钮区 -->
          <view class="flex flex-col justify-center">
            <button
              :id="`share-btn-${order.id || index}`"
              class="mb-1.5 w-14 rounded-sm bg-[#4292eb] px-0 py-1 text-xs text-white"
              :class="{ 'opacity-60': order.isGeneratingImage }"
              @tap="showShareSheet(index)"
            >
              {{ order.isGeneratingImage ? '生成中...' : '分享' }}
            </button>
            <button
              v-if="order.yourself && order.order_type !== '白条录入'"
              class="w-14 rounded-sm bg-[#f60] px-0 py-1 text-xs text-white" @tap="onChangeOrder(order)"
            >
              改单
            </button>
            <button
              v-else-if="order.yourself && order.order_type === '白条录入'"
              class="w-14 rounded-sm bg-[#808080] px-0 py-1 text-xs text-white"
            >
              改单
            </button>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="orders.length === 0" class="load-tip py-3 text-center text-xs text-gray-400">
        暂无数据
      </view>
      <view v-else-if="!hasMore && !loading" class="load-tip py-3 text-center text-xs text-gray-400">
        已加载全部数据
      </view>
      <view v-else-if="loading" class="load-tip py-3 text-center text-xs text-gray-400">
        加载中...
      </view>
    </scroll-view>

    <!-- Canvas 画布用于绘制分享图片 -->
    <canvas
      canvas-id="shareCanvas"
      :style="{
        width: `${canvasWidth}px`,
        height: `${canvasHeight}px`,
        position: 'fixed',
        right: '-999999px',
      }"
    />

    <!-- 分享选择底部弹出框 -->
    <up-popup :show="showSharePopup" mode="bottom" :round="10" @close="closeShareSheet">
      <view class="share-popup-content">
        <!-- 顶部拖拽指示器 -->
        <view class="popup-indicator" @tap="closeShareSheet" />

        <!-- 标题栏 -->
        <view class="popup-header">
          <text class="popup-title">
            选择分享方式
          </text>
          <view class="popup-close" @tap="closeShareSheet">
            <text class="popup-close-icon">
              ✕
            </text>
          </view>
        </view>

        <!-- 分享按钮区域 -->
        <view class="share-buttons">
          <button
            class="share-button green-btn"
            open-type="share"
            :data-order-index="currentShareOrderIndex"
            data-share-type="all"
            @tap="setShareType('all')"
          >
            <view class="btn-icon green-icon">
              <view class="doc-icon">
                <text class="currency-symbol">
                  ¥
                </text>
              </view>
            </view>
            <text class="btn-text green-text">
              全部赊欠分享
            </text>
          </button>

          <button
            class="share-button orange-btn"
            open-type="share"
            :data-order-index="currentShareOrderIndex"
            data-share-type="current"
            @tap="setShareType('current')"
          >
            <view class="btn-icon orange-icon">
              <view class="doc-icon">
                <view class="doc-line" />
                <view class="doc-line" />
                <view class="doc-line" />
              </view>
            </view>
            <text class="btn-text orange-text">
              本条订单分享
            </text>
          </button>
        </view>

        <!-- 复选框 -->
        <view class="checkbox-wrapper" @tap="toggleCheckbox">
          <view class="checkbox" :class="{ checked: getPhoneChecked }">
            <text v-if="getPhoneChecked" class="check-mark">
              ✓
            </text>
          </view>
          <text class="checkbox-label">
            获取买家手机号，降低坏账风险
          </text>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { onShareAppMessage } from '@dcloudio/uni-app';
import { onMounted, ref } from 'vue';
import { getMemberLists } from '@/api/member';
import { getOrderData, updateOrderData } from '@/api/order';
import { useUserStore } from '@/store';

// 订单项类型定义
interface OrderDetail {
  goods_name: string;
  goods_id?: number;
  unit: string;
  weight?: number;
  num?: number;
  price: number;
  goods_price?: number;
  total_price?: number;
  store_id?: number; // 店铺ID
  order_detail_fujiafei?: Array<{
    name: string;
    total: number;
  }>;
}

interface OrderItem {
  id: number;
  orderId?: string;
  piao_num?: string;
  buyerName?: string;
  maijia?: string;
  amount?: number;
  shishou?: number;
  yingshou?: number;
  payType?: string;
  status: number;
  summary?: string;
  order_detail?: OrderDetail[];
  createTime?: string;
  add_time?: string;
  opener?: string;
  user?: {
    id?: number;
    name?: string;
  };
  yourself?: boolean;
  order_type?: string;
  fid?: number;
  huan?: number;
  notes?: string;
  zuofei?: number;
  maijia_id?: number;
  imageUrl?: string;
  shareImageUrl?: string;
  isGeneratingImage?: boolean;
}

const keyword = ref('');
const orders = ref<OrderItem[]>([]);
const page = ref(1);
const limit = ref(10);
const hasMore = ref(true);
const loading = ref(false);
const refreshing = ref(false);

// 分享弹窗相关
const showSharePopup = ref(false);
const currentShareOrderIndex = ref(-1);
const getPhoneChecked = ref(true);
const currentShareType = ref<'all' | 'current' | ''>(''); // 当前选择的分享类型

// Canvas 相关
const canvasWidth = ref(375);
const canvasHeight = ref(300);

// 用户 store
const userStore = useUserStore();

// 初始加载数据
onMounted(() => {
  // 初始化 canvas 尺寸
  uni.getSystemInfo({
    success: (res) => {
      canvasWidth.value = res.screenWidth;
      canvasHeight.value = res.screenWidth * 0.8; // 保持 5:4 比例
    },
  });

  fetchOrders();
});

// 获取订单数据
async function fetchOrders(reset = true) {
  try {
    loading.value = true;

    if (reset) {
      page.value = 1;
      orders.value = [];
    }

    const params = {
      keywords: keyword.value,
      page: page.value,
      limit: limit.value,
    };

    const res = await getOrderData(params);

    if (res.code === 200) {
      // 处理返回数据
      const orderList = res.data.data || [];

      if (reset) {
        orders.value = orderList;
      }
      else {
        orders.value = [...orders.value, ...orderList];
      }

      // 判断是否还有更多数据
      if (res.data.total && res.data.per_page && res.data.current_page) {
        // 如果返回了分页信息，则使用分页信息判断
        const total = res.data.total;
        const perPage = res.data.per_page;
        const currentPage = res.data.current_page;
        hasMore.value = total > perPage * currentPage;
      }
      else {
        // 否则根据返回数据长度判断
        hasMore.value = orderList.length >= limit.value;
      }

      // 更新页码
      page.value++;
    }
    else {
      hasMore.value = false;
    }
  }
  catch (error) {
    console.error('获取订单数据失败', error);
    uni.showToast({
      title: '获取订单数据失败',
      icon: 'none',
    });
    hasMore.value = false;
  }
  finally {
    loading.value = false;
    if (refreshing.value) {
      refreshing.value = false;
      uni.stopPullDownRefresh();
    }
  }
}

// 搜索
const onSearch = () => {
  fetchOrders(true);
};

// 清除关键词
const clearKeyword = () => {
  keyword.value = '';
  fetchOrders(true);
};

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true;
  fetchOrders(true);
};

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    fetchOrders(false);
  }
};

// 筛选
const onFilter = () => {
  console.log('点击筛选');
  // TODO: 实现筛选功能
};

// 返回
const onBack = () => {
  uni.navigateBack();
};

// 格式化订单详情
const formatOrderDetail = (details?: OrderDetail[]) => {
  if (!details || details.length === 0) return '';

  return details.map((item) => {
    if (item.unit === '公斤' || item.unit === '斤') {
      return `${item.goods_name} ${item.weight}${item.unit}×${item.price}`;
    }
    else {
      return `${item.goods_name} ${item.num}${item.unit}×${item.price}`;
    }
  }).join(' ');
};

// 改单
function onChangeOrder(order: OrderItem) {
  // 检查订单信息是否存在
  if (!order || !order.id) {
    uni.showToast({
      title: '订单数据不存在',
      icon: 'none',
    });
    return;
  }

  // 如果是白条录入，不允许改单
  if (order.order_type === '白条录入') {
    uni.showToast({
      title: '白条录入订单不能改单',
      icon: 'none',
    });
    return;
  }

  // 显示加载提示
  uni.showLoading({
    title: '处理中...',
  });

  // 调用改单接口
  updateOrderData({ id: order.id }).then((res) => {
    uni.hideLoading();

    if (res && res.code === 200) {
      uni.showToast({
        title: '改单成功',
        icon: 'success',
      });

      // 成功后跳转到购物车页面
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/cart/index',
        });
      }, 1500);
    }
    else {
      uni.showToast({
        title: res?.msg || '改单失败',
        icon: 'none',
      });
    }
  }).catch((err) => {
    uni.hideLoading();
    uni.showToast({
      title: '改单失败，请重试',
      icon: 'none',
    });
    console.error('改单失败:', err);
  });
}

// 作废订单
function _zuofeiOrder(id: number) {
  uni.showModal({
    title: '提示',
    content: '确定要作废此订单吗？',
    success(res) {
      if (res.confirm) {
        console.log('用户点击确定', id);
        // TODO: 调用作废订单API
      }
    },
  });
}

// 更新订单 (旧版保留，现在合并到onChangeOrder函数中)
function _updateOrder(id: number) {
  onChangeOrder({ id, status: 1, yourself: true });
}

// 打印订单
function _printOrder(order: OrderItem) {
  console.log('打印订单', order);
  // TODO: 实现打印功能
}

// 显示分享选择弹框
function showShareSheet(orderIndex: number) {
  currentShareOrderIndex.value = orderIndex;
  showSharePopup.value = true;
  currentShareType.value = '';
}

// 关闭分享选择弹框
function closeShareSheet() {
  showSharePopup.value = false;
  setTimeout(() => {
    currentShareOrderIndex.value = -1;
    currentShareType.value = '';
  }, 300);
}

// 切换复选框状态
function toggleCheckbox() {
  getPhoneChecked.value = !getPhoneChecked.value;
}

// 设置分享类型
function setShareType(type: 'all' | 'current') {
  currentShareType.value = type;
  // 关闭弹窗
  setTimeout(() => {
    closeShareSheet();
  }, 100);
}

// 创建赊欠分享图片（类似 debt.vue 的逻辑）
function createDebtShareImage(buyer: any, index: number): Promise<string> {
  return new Promise((resolve, reject) => {
    // @ts-expect-error - uni-app canvas API
    const ctx = uni.createCanvasContext('shareCanvas');

    // 设置背景色
    ctx.setFillStyle('#f5fafe');
    ctx.fillRect(0, 0, canvasWidth.value, canvasHeight.value);

    // 添加边框
    ctx.setStrokeStyle('#f0f0f0');
    ctx.setLineWidth(1);
    ctx.strokeRect(0, 0, canvasWidth.value, canvasHeight.value);

    // 绘制买家名称（标题）- 加粗效果
    ctx.setFillStyle('#000000');
    ctx.setFontSize(36);
    ctx.setTextAlign('left');
    // 多次绘制模拟加粗
    ctx.fillText(buyer.maijia, 29, 60);
    ctx.fillText(buyer.maijia, 29.5, 60);
    ctx.fillText(buyer.maijia, 29, 60.5);
    ctx.fillText(buyer.maijia, 29.5, 60.5);

    // 绘制副标题 "赊欠金额" - 字体较大
    ctx.setFillStyle('#999999');
    ctx.setFontSize(24);
    ctx.fillText('赊欠金额', 30, 100);

    // 绘制订单数 "(X单)" - 字体较小，并留有间距
    const labelWidth = ctx.measureText('赊欠金额').width;
    ctx.setFontSize(20);
    ctx.fillText(`(${buyer.no_pay_num}单)`, 30 + labelWidth + 8, 100);

    // 绘制手机号（如果有）
    if (buyer.phone) {
      ctx.setFillStyle('#999999');
      ctx.setFontSize(24);
      const labelWidth2 = ctx.measureText('赊欠金额').width;
      ctx.setFontSize(20);
      const unitWidth = ctx.measureText(`(${buyer.no_pay_num}单)`).width;
      ctx.setFontSize(18);
      ctx.fillText(`（${buyer.phone}）`, 30 + labelWidth2 + 8 + unitWidth + 10, 100);
    }

    // 绘制金额（大号绿色）- 加粗效果
    ctx.setFillStyle('#3abe2c');
    ctx.setFontSize(48);
    ctx.setTextAlign('left');
    const amountText = `¥${formatNumber(buyer.sheqian_total)}`;
    // 多次绘制模拟加粗
    ctx.fillText(amountText, 30, 160);
    ctx.fillText(amountText, 30.5, 160);
    ctx.fillText(amountText, 30, 160.5);
    ctx.fillText(amountText, 30.5, 160.5);

    // 计算日期范围（假设从当前日期往前推 sheqian_day 天）
    const endDate = new Date();
    const startDate = new Date();
    startDate.setDate(endDate.getDate() - Number(buyer.sheqian_day || 0));
    const dateRange = `${formatDate(startDate)} 至 ${formatDate(endDate)}`;

    // 绘制日期范围
    ctx.setFillStyle('#666666');
    ctx.setFontSize(18);
    ctx.fillText(dateRange, 30, 200);

    // 绘制底部绿色渐变按钮区域（带圆角）
    const btnX = 30;
    const btnY = canvasHeight.value - 70;
    const btnWidth = canvasWidth.value - 60;
    const btnHeight = 50;
    const btnRadius = 2;

    // 绘制圆角矩形
    ctx.beginPath();
    ctx.moveTo(btnX + btnRadius, btnY);
    ctx.lineTo(btnX + btnWidth - btnRadius, btnY);
    ctx.arcTo(btnX + btnWidth, btnY, btnX + btnWidth, btnY + btnRadius, btnRadius);
    ctx.lineTo(btnX + btnWidth, btnY + btnHeight - btnRadius);
    ctx.arcTo(btnX + btnWidth, btnY + btnHeight, btnX + btnWidth - btnRadius, btnY + btnHeight, btnRadius);
    ctx.lineTo(btnX + btnRadius, btnY + btnHeight);
    ctx.arcTo(btnX, btnY + btnHeight, btnX, btnY + btnHeight - btnRadius, btnRadius);
    ctx.lineTo(btnX, btnY + btnRadius);
    ctx.arcTo(btnX, btnY, btnX + btnRadius, btnY, btnRadius);
    ctx.closePath();

    // 填充渐变色（135度,从青绿到草绿）
    const gradient = ctx.createLinearGradient(btnX, btnY, btnX + btnWidth, btnY + btnHeight);
    gradient.addColorStop(0.2, '#009481'); // 青绿色（20%）
    gradient.addColorStop(1, '#52b316'); // 草绿色（100%）
    ctx.setFillStyle(gradient);
    ctx.fill();

    // 绘制按钮文字
    ctx.setFillStyle('#ffffff');
    ctx.setFontSize(20);
    ctx.setTextAlign('center');
    ctx.fillText('查看订单详情', canvasWidth.value / 2, btnY + btnHeight / 2 + 6);

    // 绘制完成后，生成图片
    ctx.draw(false, () => {
      setTimeout(() => {
        uni.canvasToTempFilePath({
          canvasId: 'shareCanvas',
          success: (res) => {
            console.log('分享图片生成成功:', res.tempFilePath);
            orders.value[index].shareImageUrl = res.tempFilePath;
            orders.value[index].isGeneratingImage = false;
            resolve(res.tempFilePath);
          },
          fail: (err) => {
            console.error('生成图片失败:', err);
            orders.value[index].isGeneratingImage = false;
            reject(err);
          },
        });
      }, 300); // 延迟确保绘制完成
    });
  });
}

// 工具函数
const formatNumber = (num: number) => num.toLocaleString();

const formatDate = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const formatDateWithSeconds = (dateStr: string | undefined) => {
  if (!dateStr) return '-';
  try {
    const date = new Date(dateStr);
    const pad = (num: number) => String(num).padStart(2, '0');
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
  }
  catch {
    return dateStr;
  }
};

// 创建分享图片
function createShareImage(order: OrderItem, index: number): Promise<string> {
  return new Promise((resolve, reject) => {
    // @ts-expect-error - uni-app canvas API
    const ctx = uni.createCanvasContext('shareCanvas');

    // 设置背景色
    ctx.setFillStyle('#f5fafe');
    ctx.fillRect(0, 0, canvasWidth.value, canvasHeight.value);

    // 添加边框
    ctx.setStrokeStyle('#f0f0f0');
    ctx.setLineWidth(1);
    ctx.strokeRect(0, 0, canvasWidth.value, canvasHeight.value);

    // 绘制买家名称（标题）- 加粗效果
    const buyerName = order.maijia || order.buyerName || '未知买家';
    ctx.setFillStyle('#000000');
    ctx.setFontSize(36);
    ctx.setTextAlign('left');
    // 多次绘制模拟加粗
    ctx.fillText(buyerName, 29, 60);
    ctx.fillText(buyerName, 29.5, 60);
    ctx.fillText(buyerName, 29, 60.5);
    ctx.fillText(buyerName, 29.5, 60.5);

    // 绘制副标题 "订单金额" - 字体较大
    ctx.setFillStyle('#999999');
    ctx.setFontSize(24);
    ctx.fillText('订单金额', 30, 100);

    // 绘制订单号 "(单号:xxx)" - 字体较小，并留有间距
    const orderNum = order.piao_num || order.orderId || order.id;
    const labelWidth = ctx.measureText('订单金额').width;
    ctx.setFontSize(20);
    ctx.fillText(`（单号:${orderNum}）`, 30 + labelWidth + 8, 100);

    // 绘制金额（大号绿色）- 加粗效果
    const amount = order.status !== 0 ? order.shishou : order.yingshou;
    ctx.setFillStyle('#3abe2c');
    ctx.setFontSize(48);
    ctx.setTextAlign('left');
    const amountText = `¥${formatNumber(amount || 0)}`;
    // 多次绘制模拟加粗
    ctx.fillText(amountText, 30, 160);
    ctx.fillText(amountText, 30.5, 160);
    ctx.fillText(amountText, 30, 160.5);
    ctx.fillText(amountText, 30.5, 160.5);

    // 绘制订单时间（精确到秒）
    const orderTime = `订单时间：${formatDateWithSeconds(order.add_time || order.createTime)}`;
    ctx.setFillStyle('#666666');
    ctx.setFontSize(18);
    ctx.fillText(orderTime, 30, 200);

    // 绘制底部绿色渐变按钮区域（带圆角）
    const btnX = 30;
    const btnY = canvasHeight.value - 70;
    const btnWidth = canvasWidth.value - 60;
    const btnHeight = 50;
    const btnRadius = 2;

    // 绘制圆角矩形
    ctx.beginPath();
    ctx.moveTo(btnX + btnRadius, btnY);
    ctx.lineTo(btnX + btnWidth - btnRadius, btnY);
    ctx.arcTo(btnX + btnWidth, btnY, btnX + btnWidth, btnY + btnRadius, btnRadius);
    ctx.lineTo(btnX + btnWidth, btnY + btnHeight - btnRadius);
    ctx.arcTo(
      btnX + btnWidth,
      btnY + btnHeight,
      btnX + btnWidth - btnRadius,
      btnY + btnHeight,
      btnRadius,
    );
    ctx.lineTo(btnX + btnRadius, btnY + btnHeight);
    ctx.arcTo(btnX, btnY + btnHeight, btnX, btnY + btnHeight - btnRadius, btnRadius);
    ctx.lineTo(btnX, btnY + btnRadius);
    ctx.arcTo(btnX, btnY, btnX + btnRadius, btnY, btnRadius);
    ctx.closePath();

    // 填充渐变色（135度,从青绿到草绿）
    const gradient = ctx.createLinearGradient(btnX, btnY, btnX + btnWidth, btnY + btnHeight);
    gradient.addColorStop(0.2, '#009481'); // 青绿色（20%）
    gradient.addColorStop(1, '#52b316'); // 草绿色（100%）
    ctx.setFillStyle(gradient);
    ctx.fill();

    // 绘制按钮文字
    ctx.setFillStyle('#ffffff');
    ctx.setFontSize(20);
    ctx.setTextAlign('center');
    ctx.fillText('查看订单详情', canvasWidth.value / 2, btnY + btnHeight / 2 + 6);

    // 绘制完成后，生成图片
    ctx.draw(false, () => {
      setTimeout(() => {
        uni.canvasToTempFilePath({
          canvasId: 'shareCanvas',
          success: (res) => {
            console.log('分享图片生成成功:', res.tempFilePath);
            orders.value[index].shareImageUrl = res.tempFilePath;
            orders.value[index].isGeneratingImage = false;
            resolve(res.tempFilePath);
          },
          fail: (err) => {
            console.error('生成图片失败:', err);
            orders.value[index].isGeneratingImage = false;
            reject(err);
          },
        });
      }, 300); // 延迟确保绘制完成
    });
  });
}

// 注册分享方法
onShareAppMessage(async (options: any) => {
  // 从 button 的 dataset 中获取订单索引和分享类型
  if (
    options.from === 'button'
    && typeof options.target?.dataset?.orderIndex !== 'undefined'
  ) {
    const orderIndex = Number(options.target.dataset.orderIndex);
    const shareType = options.target?.dataset?.shareType || currentShareType.value;
    const order = orders.value[orderIndex];
    console.log('order买家信息分分享:', order);
    if (!order) {
      return {
        title: '订单分享',
        path: '/pages/order/order',
      };
    }

    // 显示 loading
    uni.showLoading({
      title: '正在生成分享图片...',
      mask: true,
    });

    // 标记正在生成
    orders.value[orderIndex].isGeneratingImage = true;

    try {
      // 目标小程序的 appId 和路径
      const targetAppId = 'wx26980c7935e571cc';
      const storeId = userStore.userInfo?.admin_id || '';
      const storeName = encodeURIComponent(userStore.dangkou_name || '云批宝');
      const username = encodeURIComponent(userStore.user_name || '');

      // 获取买家ID
      const maijiaId = order.maijia_id
        || order.fid
        || 0;

      // 根据分享类型选择不同的逻辑
      if (shareType === 'all') {
        // 全部赊欠分享 - 需要获取买家的完整赊欠信息
        const buyerName = order.maijia || order.buyerName || '未知买家';

        // 通过 API 获取买家的完整赊欠信息
        let buyerInfo = null;
        try {
          const memberRes = await getMemberLists({
            keywords: buyerName, // 通过买家名称搜索
            page: 1,
            limit: 100, // 获取足够多的数据以便找到对应买家
            options_order_status_value: '2',
            options_maijia_status_value: '999',
          });

          if (memberRes.code === 200 && memberRes.data?.data?.data) {
            // 查找匹配的买家（通过 maijia_id 或名称）
            buyerInfo = memberRes.data.data.data.find(
              (item: any) => item.maijia_id === maijiaId || item.maijia === buyerName,
            );
          }
        }
        catch (error) {
          console.error('获取买家赊欠信息失败:', error);
        }

        // 创建买家对象（使用 API 返回的真实数据）
        const buyer = {
          maijia: buyerName,
          maijia_id: maijiaId,
          phone: order?.maijiainfo?.mobile, // 电话信息需要从其他地方获取，暂时留空
          sheqian_total: buyerInfo?.sheqian_total || 0, // 真实的赊欠总额
          sheqian_day: Number(buyerInfo?.sheqian_day) || 0, // 真实的赊欠天数
          no_pay_num: buyerInfo?.no_pay_num || '0', // 真实的未支付订单数
        };

        // 使用类似 debt.vue 的方式创建分享图片
        const imagePath = await createDebtShareImage(buyer, orderIndex);
        uni.hideLoading();

        // 构建小程序页面路径：跳转到对账页面（传递 maijia_id 用于过滤）
        const targetPath = encodeURIComponent(
          `pages/reconciliation/reconciliation?storeId=${storeId}&storeName=${storeName}&username=${username}&maijia_id=${maijiaId}`,
        );

        return {
          title: `${userStore.real_name || '商家'}`,
          path: `/pages/common/share/redirect?targetAppId=${targetAppId}&targetPath=${targetPath}&maijia=${encodeURIComponent(
            buyerName,
          )}&amount=${buyer.sheqian_total || 0}&days=${buyer.sheqian_day || 0}&phone=${buyer.phone || ''}&shopName=${storeName}&maijia_id=${maijiaId}`,
          imageUrl: imagePath,
        };
      }
      else {
        // 本条订单分享 - 使用当前页面的分享逻辑
        const imagePath = await createShareImage(order, orderIndex);
        uni.hideLoading();

        const detailPath = `/pages/orderDetail/orderDetail?orderId=${order.id}&storeName=${storeName}&username=${encodeURIComponent(username)}&totalPaying=${order.status !== 0 ? order.shishou : order.yingshou}`;

        // 获取订单时间
        const orderTime = order.add_time || order.createTime || '';
        // 获取订单金额（根据订单状态选择）
        const orderAmount = order.status !== 0 ? (order.shishou || 0) : (order.yingshou || 0);

        return {
          title: `${userStore.real_name || '商家'}`,
          path: `/pages/common/share/redirect?targetAppId=${targetAppId}&targetPath=${encodeURIComponent(detailPath)}&maijia=${encodeURIComponent(
            order.maijia || '',
          )}&amount=${orderAmount}&orderId=${order.id}&orderTime=${encodeURIComponent(orderTime)}&shopName=${storeName}`,
          imageUrl: imagePath,
        };
      }
    }
    catch (error) {
      uni.hideLoading();
      uni.showToast({
        title: '生成图片失败',
        icon: 'none',
      });
      console.error('分享失败:', error);
      orders.value[orderIndex].isGeneratingImage = false;
    }
  }

  // 默认分享内容
  return {
    title: '订单分享',
    path: '/pages/order/order',
  };
});

// 添加分享功能（保留原有的 useShare hook，但是注释掉避免冲突）
// const {onShareAppMessage} = useShare({
//   title: '订单管理',
//   path: '/pages/order/order',
//   query: '',
// });

// onShareAppMessage();
</script>

<style scoped>
.fixed-header {
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  z-index: 100;
  background-color: #fff;
}

.order-list {
  position: absolute;
  inset: calc(var(--status-bar-height) + 74px) 0 0;

  /* 状态栏高度 + 头部导航(44px) + 搜索框高度(50px) */
  padding-top: 40px;
  padding-bottom: 24px;
  background-color: #f5f5f5;
}

.action-btn {
  display: inline-block;
  padding: 2px 6px;
  margin-left: 8px;
  font-size: 12px;
  color: #fff;
  border-radius: 3px;
}

/* 分享弹出框样式 */
.share-popup-content {
  padding: 0 0 20rpx;
  background-color: #fff;
}

.popup-indicator {
  width: 80rpx;
  height: 8rpx;
  margin: 16rpx auto;
  cursor: pointer;
  background-color: #e5e5e5;
  border-radius: 4rpx;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx 32rpx;
  border-bottom: 1px solid #f0f0f0;
}

.popup-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.popup-close {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 56rpx;
  height: 56rpx;
  background-color: #f5f5f5;
  border-radius: 50%;
}

.popup-close-icon {
  font-size: 36rpx;
  color: #666;
}

.share-buttons {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  padding: 0 32rpx;
  margin-bottom: 16rpx;
}

.share-button {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  width: 100%;
  padding: 16rpx 20rpx;
  margin: 0;
  line-height: normal;
  text-align: left;
  background: transparent;
  border: 2rpx solid #e5e5e5;
  border-radius: 14rpx;
}

.share-button::after {
  border: none;
}

.green-btn {
  background: #f6ffed;
  border-color: #b7eb8f;
}

.orange-btn {
  background: #fff7e6;
  border-color: #ffd591;
}

.btn-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 70rpx;
  height: 70rpx;
  margin-right: 20rpx;
  border-radius: 14rpx;
}

.green-icon {
  background: #52c41a;
}

.orange-icon {
  background: #ff9500;
}

.doc-icon {
  display: flex;
  flex-direction: column;
  gap: 6rpx;
  align-items: center;
  justify-content: center;
}

.currency-symbol {
  font-size: 42rpx;
  font-weight: bold;
  color: #fff;
}

.doc-line {
  width: 40rpx;
  height: 6rpx;
  background: #fff;
  border-radius: 3rpx;
}

.btn-text {
  font-size: 30rpx;
  font-weight: 500;
}

.green-text {
  color: #52c41a;
}

.orange-text {
  color: #ff9500;
}

.checkbox-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16rpx 32rpx 0;
}

.checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36rpx;
  height: 36rpx;
  margin-right: 16rpx;
  border: 2rpx solid #52c41a;
  border-radius: 6rpx;
  transition: all 0.3s;
}

.checkbox.checked {
  background: #52c41a;
}

.check-mark {
  font-size: 24rpx;
  font-weight: bold;
  color: #fff;
}

.checkbox-label {
  font-size: 26rpx;
  color: #666;
}
</style>
